package com.iwomy.secureplat.platform.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.iwomy.secureplat.common.excel.annotation.ResponseExcel;
import com.iwomy.secureplat.platform.dto.BasicDeviceDTO;
import com.iwomy.secureplat.platform.excel.DeviceOverviewExcel;
import com.iwomy.secureplat.platform.service.BasicDeviceService;
import com.iwomy.secureplat.platform.service.RealTimeDataService;
import com.iwomy.secureplat.platform.transmission.entity.SensorTransmissionData;
import com.iwomy.secureplat.platform.transmission.entity.SensorTransmissionDataDetails;
import com.iwomy.secureplat.platform.vo.BasicDeviceVO;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备总览
 *
 * @author pig
 * @date 2024-01-29 09:58:08
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/deviceOverview")
@Tag(description = "deviceOverview", name = "设备总览")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class DeviceOverviewController {

	private final BasicDeviceService basicDeviceService;

	private final RealTimeDataService realTimeDataService;

	/**
	 * 导出excel 表格
	 *
	 * @param basicDeviceDTO
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	public List<DeviceOverviewExcel> export(@ParameterObject BasicDeviceDTO basicDeviceDTO) {
		List<BasicDeviceVO> export = basicDeviceService.getdeviceList(basicDeviceDTO);
		for (BasicDeviceVO record : export) {
			SensorTransmissionData sensorTransmissionData = realTimeDataService.getOneByImei(record.getImei());
			record.setSensorTransmissionData(sensorTransmissionData);
		}
		for (BasicDeviceVO deviceVO : export) {
			if (ObjectUtil.isEmpty(deviceVO.getSensorTransmissionData())) {
				deviceVO.setContent(null);
			} else {
				List<SensorTransmissionDataDetails> list = deviceVO.getSensorTransmissionData().getSensorTransmissionDataDetailsList();
				if (ObjectUtil.isEmpty(list)) {
					deviceVO.setContent(null);
				} else {
					String content = list.stream()
							.map(details -> details.getGasTypeIdAndUnit() + ":" + details.getSensorVal())
							.collect(Collectors.joining("； "));
					deviceVO.setContent(content);
				}
			}

			if (deviceVO.getOnline() == 10) {
				deviceVO.setDeviceStateName("离线");
			} else if (deviceVO.getDeviceState() == 20) {
				deviceVO.setDeviceStateName("在线");
			}
		}
		List<DeviceOverviewExcel> excelExport = BeanUtil.copyToList(export, DeviceOverviewExcel.class);
		return excelExport;
	}

}